package com.ruslan.magaz.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ruslan.magaz.domain.Address;
import com.ruslan.magaz.domain.Cart;
import com.ruslan.magaz.domain.Customer;
import com.ruslan.magaz.domain.Order;
import com.ruslan.magaz.domain.OrderStatus;
import com.ruslan.magaz.domain.OrderedItem;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.ItemService;
import com.ruslan.magaz.service.OrderService;
import com.ruslan.magaz.service.UserService;


@Controller
@RequestMapping("/order")

public class OrderController {
	
	private static final int ORDER_PAGE_SIZE = 15;
	private static final int ITEMS_PAGE_SIZE = 15;
	@Autowired
	private UserService userService;
	@Autowired
	private ItemService itemService;
	@Autowired
	private OrderService orderService;
	
//	List<OrderLine> getOrderLines(List<Order> orders){
//		for (Order o:orders){
//			OrderLine orderLine = new OrderLine();
//			orderLine.setOrderId(o.getOrderId());
//			
//			Date orderDate = null;
//			for (OrderStatus os: o.getOrderStatuses()){
//				if (os.getOrderStatusId() == OrderService.INITIAL_STATUS_ID){
//					orderDate = os.getStatusTime();
//					break;
//				}
//			}
//			orderLine.setOrderDate(orderDate);
//			
//			int totalPrice = 0;
//			for (OrderedItem oi: o.getOrderedItems()){
//				
//			}
//	}
	
	
	@RequestMapping(value="/cart", method = RequestMethod.GET)
    public String showCart(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
			HttpSession session = req.getSession(false);
	        Cart cart = (Cart) session.getAttribute("cart");
	        Integer userId = (Integer) session.getAttribute("userId");
	        if (userId != null){
	        	model.addAttribute("loggedIn", true);
	        }
	        Order order = new Order();
	        if (cart == null || cart.getProductMap().size()==0){
	        	model.addAttribute("notEmpty", false);
	        }else{
			    List<OrderedItem> orderedItems = itemService.getOrderedItemsFromCart(order, cart.getProductMap());
			    order.setOrderedItems(orderedItems);
			    model.addAttribute("order", order);
			    model.addAttribute("notEmpty", true);
	        }
	        
		 	return "tiles/cart";
	  }
	
	@RequestMapping(value="/cart", method = RequestMethod.POST)
    public String postCart(HttpServletRequest req, HttpServletResponse res,  Model model, @Valid @ModelAttribute("order") Order order, BindingResult bindingResult) throws ServletException, IOException{
		HttpSession session = req.getSession(false);
		if(bindingResult.hasErrors()){
    		List<OrderedItem> orderedItems = order.getOrderedItems();
    		for (OrderedItem orderedItem: order.getOrderedItems()){
    			orderedItem.getProduct().setName(itemService.getProductById(orderedItem.getProduct().getProductId()).getName());
    		}
    		
		    order.setOrderedItems(orderedItems);
		    Integer userId = (Integer) session.getAttribute("userId");
	        if (userId != null){
	        	model.addAttribute("loggedIn", true);
	        }
    		model.addAttribute("order", order);
    		model.addAttribute("notEmpty", true);
    		return "tiles/cart";
    	}
	    if ("ok".equals(req.getParameter("action"))){
	    	
	    	 Cart cart = new Cart();
	    	 cart.setProductMap(itemService.getCartFromOrder(order));
	    	 session.setAttribute("cart", cart);
	    	 return "redirect:/home";
	     }else{
	    	int userId = (Integer) session.getAttribute("userId");
	    	Customer customer = userService.getUserById(userId).getCustomer();
	    	Order newOrder = new Order();
	    	newOrder.setDiscount(orderService.calculateDiscount(userId));
	    	newOrder.setCustomer(customer);
	    	orderService.setInitialStatus(newOrder);
	    	Map<Integer, Integer> itemMap = itemService.getCartFromOrder(order);
	    	newOrder.setOrderedItems(itemService.getOrderedItemsFromCart(newOrder, itemMap));
//	    	Order order = new Order();
//	    	order.setOrderedItems(orderedItems);
	    	orderService.addOrder(userId, newOrder);
	    	Cart cart = new Cart();
	    	session.setAttribute("cart", cart);
	    return "redirect:/order";
	     }
	  }
	
	@RequestMapping(value="/cart/remove")
    public String removeFromCart(HttpServletRequest req, HttpServletResponse res, @RequestParam int id, Model model) throws ServletException, IOException{
		HttpSession session = req.getSession(false);
		Cart cart = (Cart) session.getAttribute("cart");
		cart.remove(id);
		session.setAttribute("cart", cart);
	    return "redirect:/order/cart";
	  }
	
	@RequestMapping(value="", method = RequestMethod.GET)
    public String orderCart(HttpServletRequest req, HttpServletResponse res, @RequestParam(required = false) Integer pageNum, Model model) throws ServletException, IOException{
		if (pageNum == null){
			pageNum=1;
		}
		HttpSession session = req.getSession(false);
		int userId = (Integer) session.getAttribute("userId");
//		List<Order> orders = orderService.getAllOrdersForUser(userId);
		List rawOrderLines = orderService.getOrderLines(userId, pageNum, ORDER_PAGE_SIZE);
		List<OrderLine> orderLines = OrderLine.getOrderLines(rawOrderLines); 
		model.addAttribute("orderLines", orderLines);
		model.addAttribute("lastPageNum", orderService.ordersForUserPageCount(userId, ORDER_PAGE_SIZE));
	    return "tiles/orders";
	  }
	
	@RequestMapping(value="/view", method = RequestMethod.GET)
    public String viewOrder(HttpServletRequest req, HttpServletResponse res,@RequestParam int orderId, @RequestParam(required = false) Integer pageNum, Model model) throws ServletException, IOException{
		if (pageNum == null){
			pageNum=1;
		}
		HttpSession session = req.getSession(false);
		int userId = (Integer) session.getAttribute("userId");
		User user = orderService.getUsersforOrder(orderId);
		if (userId != user.getUserId()){
			return "redirect:/home";
		}
		List<OrderedItem> orderedItems = orderService.getOrderedItemsForOrder(orderId, pageNum, ITEMS_PAGE_SIZE);
		model.addAttribute("orderedItems", orderedItems);
		model.addAttribute("orderId", orderId);
		model.addAttribute("lastPageNum", orderService.orderedItemsForOrderPageCount(orderId, ORDER_PAGE_SIZE));
	    return "tiles/order";
	  }
	
	@RequestMapping(value="/status", method = RequestMethod.GET)
    public String viewStatus(HttpServletRequest req, HttpServletResponse res,@RequestParam int orderId, Model model) throws ServletException, IOException{
		HttpSession session = req.getSession(false);
		int userId = (Integer) session.getAttribute("userId");
		User user = orderService.getUsersforOrder(orderId);
		if (userId != user.getUserId()){
			return "redirect:/home";
		}
		List<OrderStatus> orderStatuses = orderService.getOrderStatusesForOrder(orderId);
		model.addAttribute("orderStatuses", orderStatuses);
		model.addAttribute("orderId", orderId);

	    return "tiles/orderStatuses";
	  }
	
}
